package com.cy.store.controller;

import com.cy.store.service.ex.*;
import com.cy.store.utill.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

public class BaseController {
    public static int OK = 200;

    /**
     *异常处理类，当出现ServcieException类的异常时，调用jsonresult方法进行解决
     * @param e 异常
     * @return result封装了异常信息
     */
    @ExceptionHandler(ServcieException.class)
    public JsonResult<Void> handlerException(Throwable e){
        JsonResult<Void> result = new JsonResult<>(e);
        //4001 1 为具体的异常
        if(e instanceof UsernameDuplicateException){
            result.setState(4000);
        }else if(e instanceof UserNotFoundException){
            result.setState(4001);
        }else if(e instanceof PasswordNotMatchException){
            result.setState(4002);
        }
        else if (e instanceof AddressCountLimitException) {
            result.setState(4003);
        }else if (e instanceof AddressNotFoundException) {
            result.setState(4004);
        } else if (e instanceof AccessDeniedException) {
            result.setState(4005);
        }else if (e instanceof ProductNotFoundException) {
            result.setState(4006);
        }
        //5000为另一个大的异常
        else if(e instanceof InsertException){
            result.setState(5000);
        }else if(e instanceof UpdateException){
            result.setState(5001);
            //6000之后为文件上传时异常
        }else if (e instanceof FileEmptyException) {
            result.setState(6000);
        } else if (e instanceof FileSizeException) {
            result.setState(6001);
        } else if (e instanceof FileTypeException) {
            result.setState(6002);
        } else if (e instanceof FileStateException) {
            result.setState(6003);
        } else if (e instanceof FileUploadIOException) {
            result.setState(6004);
        }

        return result;
    }

    protected  final Integer getUidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }
    protected final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }
}
